<?php

require( 'config.php' );

// Version
define( 'VERSION', "1.0" );

// Database Handler
$dbh = NULL;

/**
	Connect to database
*/
function db() {

	global $dbdsn, $dbuser, $dbpass, $dbh;

	if( $dbh == NULL ) {
		$dbh = new PDO( $dbdsn, $dbuser, $dbpass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
		$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	}
}

/**
	Return array of uniq values up to max results
		$table: table name
		$col: column
		$max: maximum number of results
*/
function getList( $col, $max ) {
	
	// Connect to DB
	global $dbh, $dbtable;
	db();

	// Get list
	$sql = "SELECT DISTINCT $col FROM $dbtable ORDER BY 1 LIMIT ".(1+$max);
	$stmt = $dbh->query( $sql );
	$res = $stmt->fetchAll(PDO::FETCH_COLUMN);	// TODO: mode de récupération
	
	if( count($res) > $max ) {
		$res = NULL;
	} 
	
	return $res;
}

/**
	Get first available date
		$table: table name
		$col: column
*/
function getFirstDate( $col ) {

	
	// Connect to DB
	global $dbh, $dbtable;
	db();

	// Request first date
	$sql = "SELECT MIN( $col ) FROM $dbtable";
	$stmt = $dbh->query( $sql );
	$res = $stmt->fetch(PDO::FETCH_NUM);
	
	return $res[0];
}
